package au.com.handsunited.web.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 * @author arunda
 *
 */
public class ImageController extends AbstractController {


	private String imagesDir;
	private static final String IMG_SRC = "imgsrc";

	private static Logger logger = LoggerFactory.getLogger(ImageController.class);


	/**
	 *
	 */
	public ImageController() {
		// TODO Auto-generated constructor stub
	}



	/**
	 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String imgSrc = request.getParameter(IMG_SRC);

		if (StringUtils.isNotBlank(imgSrc)) {
			File imgFile = new File(imagesDir, imgSrc);

			if (imgSrc.endsWith(".gif")) {
				response.setContentType("image/gif");
			} else {
				response.setContentType("image/jpeg");
			}

			response.getOutputStream().write(FileUtils.readFileToByteArray(imgFile));
			response.flushBuffer();
		}

		return null;
	}


	/**
	 * @return the imagesDir
	 */
	public String getImagesDir() {
		return this.imagesDir;
	}


	/**
	 * @param imagesDir the imagesDir to set
	 */
	public void setImagesDir(String imagesDir) {
		this.imagesDir = imagesDir;
	}


}
